//
//  SyncViewController.m
//  Gradekeeper0.2
//
//  Created by Myat Thu on 09-11-24.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "SyncViewController.h"

@implementation SyncViewController

@synthesize greeting, usrnameInput, passwrdInput, loginIndicator, webData, soapResults, xmlParser;
@synthesize loginButton, registerOnline;

-(IBAction)buttonClick:(id)sender{
	
	//when the button is clicked, the indicator animates and button is disabled
	loginIndicator.hidden = FALSE;
	loginButton.enabled = FALSE;
	[loginIndicator startAnimating];
	
	recordResults = FALSE;
	
	//message for SOAP...ver1 currently tests an existing webservice @viium to ping for hello
	NSString *soapMessage = [NSString stringWithFormat:
							 @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
							 "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
							 "<soap:Body>\n"
							 "<Hello xmlns=\"http://viium.com/\">\n"
							 "<name>%@</name>\n"
							 "</Hello>\n"
							 "</soap:Body>\n"
							 "</soap:Envelope>\n", usrnameInput.text
							 ];
	NSLog(soapMessage);
	
	//URL of webservice
	NSURL *url = [NSURL URLWithString:@"http://viium.com/WebService/HelloWorld.asmx"];
	NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
	
	NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];
	
	//set HTTP header fields
	[theRequest addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
	[theRequest addValue:@"http://viium.com/Hello" forHTTPHeaderField:@"SOAPAction"];
	[theRequest addValue:msgLength forHTTPHeaderField:@"Content-Length"];
	[theRequest setHTTPMethod:@"POST"];
	[theRequest setHTTPBody:[soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
	
	NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];	
	
	if(theConnection)
	{
		webData =[[NSMutableData data] retain];
	}
	else
	{
		NSLog(@"theConnection is NULL"); //error checking
	}
	
	//release KB
	[usrnameInput resignFirstResponder];
	[passwrdInput resignFirstResponder];
	
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	[webData setLength: 0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	[webData appendData:data];
}

//error checking
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	NSLog(@"ERROR with theConenction");
	[connection release];
	[webData release];
}

//transaction is done
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	NSLog(@"DONE. Received Bytes: %d", [webData length]);
	NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
	NSLog(theXML);
	[theXML release];
	
	if( xmlParser )
	{
		[xmlParser release];
	}
	
	xmlParser = [[NSXMLParser alloc] initWithData: webData];
	[xmlParser setDelegate: self];
	[xmlParser setShouldResolveExternalEntities: YES];
	[xmlParser parse];
	
	//stop animating the indicator and set button to true
	[loginIndicator stopAnimating];	
	loginButton.enabled = TRUE;
	
	[connection release];
	[webData release];
}

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName
   attributes: (NSDictionary *)attributeDict
{
	if( [elementName isEqualToString:@"HelloResult"])
	{
		if(!soapResults)
		{
			soapResults = [[NSMutableString alloc] init];
		}
		recordResults = TRUE;
	}
}

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
	if( recordResults )
	{
		[soapResults appendString: string];
	}
}

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
	if( [elementName isEqualToString:@"HelloResult"])
	{
		recordResults = FALSE;
		greeting.text = soapResults;
		[soapResults release];
		soapResults = nil;
	}
}


- (void)didReceiveMemoryWarning {	
    [super didReceiveMemoryWarning];	
	
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

- (IBAction) btnClickMe_Clicked: (id) sender{
	
		UIAlertView *alert = [[UIAlertView alloc] 
							  initWithTitle:@"Exiting GK" 
							  message:@"You are about to exit the application to register on our website. \nAre you sure you want to continue?" 
							  delegate:self
							  cancelButtonTitle:@"Yes"
							  otherButtonTitles:nil]; 
		[alert addButtonWithTitle:@"No"];
		[alert show];
		[alert release];


} //btnClickMe_Clicked

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
 	if (buttonIndex == 0) {
			
		[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://gradeskeeper.hysniu.com"]];
    }
} //alertView

- (void)dealloc {
	[xmlParser release];
    [super dealloc];
}


@end
